/* eslint-disable no-shadow */
/* eslint-disable no-unused-vars */
import React, { memo, useState, useEffect, useCallback, useRef } from "react";
import Taro, {
  useRouter,
  useDidShow,
  usePageScroll,
  useReachBottom,
} from "@tarojs/taro";
import { useSelector, useDispatch, shallowEqual } from "react-redux";
import { updateState } from "@/store/actions/global";
import { View, Text, Image } from "@tarojs/components";
import { Loading, Empty, Tabs, Tab } from "@antmjs/vantui";
import debounce from "lodash/debounce";
import axios from "@/axios";
import { getRelationShip, getUserData, updateRelationShip } from "@/axios/api/user";
import Authorization from "@/components/Authorization";
import BackTop from "@/components/BackTop";
import Navbar from "@/components/Navbar";
import { themeColor } from "../../utils/config";
import "./index.less";

const Index = () => {
  const router = useRouter();
  const dispatch = useDispatch();
  const { globalData } = useSelector(
    (state) => ({ globalData: state.globalData }),
    shallowEqual
  );
  const { isLogin, showBackTop, systemInfo, navbarHeight, userInfo } = globalData;
  const { type = 0 } = router.params;
  const { user_id, fans = 0, follow = 0, username } = userInfo || {};
  const { screenHeight } = systemInfo;
  const [active, setActive] = useState(Number(type));
  const [isLoading, setLoading] = useState(false);
  const [ListData, setListData] = useState([]);
  const [isMore, setIsMore] = useState(false);
  const [pageNum, setPageNum] = useState(1);
  const [navbarTitle] = useState(username);
  const [flag, setFlag] = useState(false);
  const tab = [
    {
      id: 1,
      value: `我的关注(${follow})`
    },
    {
      id: 2,
      value: `我的粉丝(${fans})`
    }
  ];

  const onChange = ({ detail: { index } }) => {
    if (flag) {
      setListData([]);
      getData(index + 1, 1);
      setActive(index);
    }
  };
  const handleClick = useCallback(
    debounce(
      (type, id, username) => {
        console.log("CLICK", type, id);
        let url = "";
        if (type === "user") {
          url = `/pages/userCenter/index?user_id=${id}&username=${username}`;
        }
        if (!isLogin) {
          dispatch(
            updateState({
              isShowGrant: true,
            })
          );
        } else {
          jumpTo(url);
        }
      },
      500,
      {
        leading: true,
        trailing: false,
      }
    ),
    [isLogin]
  );
  const jumpTo = (url) => {
    Taro.navigateTo({
      url,
    });
  };
  const getUserInfoData = () => {
    axios.post(getUserData).then((res) => {
      const { data, code } = res;
      if (code === 200) {
        const { userInfo } = data;
        Taro.setStorageSync("userInfo", userInfo);
        dispatch(updateState({ userInfo }));
      }
    });
  };
  const getData = (type = 1, page = 1) => {
    setLoading(true);
    axios.post(getRelationShip, { type, page, user_id }).then((res) => {
      const { data, code } = res;
      if (code === 200) {
        // const { list, pageNum, pageSize, total } = data;
        console.log(data, res.msg);
        const { pageNum, isMore, list } = data;
        if (page === 1) {
          setListData(list);
          setIsMore(isMore)
          setPageNum(pageNum)
        } else {
          setListData((pre) => [...pre, ...list]);
          setIsMore(isMore)
          setPageNum(pageNum)
        }
      }
      setLoading(false);
    });
  };
  const handleFollow = useCallback(
    debounce(
      (follow_id, item) => {
        const { state, username } = item;
        if (state !== 0) {
          Taro.showModal({
            title: '提示',
            content: `你确定要取消关注用户\r\n"${username}"吗`,
            success: function (res) {
              if (res.confirm) {
                axios.post(updateRelationShip, { follow_id, user_id }).then(res => {
                  if (res.code === 200) {
                    getUserInfoData();
                    const { state } = res.data;
                    item.state = state;
                    setListData(pre => {
                      return [ ...pre ]
                    })
                  }
                })
              }
            }
          })
        } else {
          axios.post(updateRelationShip, { follow_id, user_id }).then(res => {
            if (res.code === 200) {
              getUserInfoData();
              const { state } = res.data;
              item.state = state;
              setListData(pre => {
                return [ ...pre ]
              })
            }
          })
        }
      },
      300,
      {
        leading: true,
        trailing: false,
      }
    ),
    []
  );
  const getListDom = (type = 1) => {
    return ListData.map((item, index) => {
      const { user_id, follow_id, username, avatar, state } = item;
      let u_id = active ? user_id : follow_id
      return (
        <View className='user-item'>
          <View className='left' onClick={() => handleClick('user', u_id, username)}>
            <View className='avatar'><Image src={avatar}></Image></View>
            <Text className='username'>{username}</Text>
          </View>
          <View className='right'>
            <View className={`btn-follow ${state === 0 ? 'active' : ''}`} onClick={() => handleFollow(u_id, item)}><Text>{item.state ? (item.state === 1 ? '已关注' : '互相关注') : '关注'}</Text></View>
          </View>
        </View>
      );
    });
  };
  useEffect(() => {
    if (!isLogin) {
      dispatch(
        updateState({
          isShowGrant: true,
        })
      );
      return;
    }
    getData(active + 1);
    getUserInfoData();
    setFlag(true);
  }, [isLogin, dispatch]);
  useDidShow(() => {
    if (flag) {
      getData(active + 1);
      getUserInfoData();
    }
  })
  usePageScroll((res) => {
    const flag = res.scrollTop > screenHeight * 1.5;
    if (flag !== showBackTop) {
      dispatch(
        updateState({
          showBackTop: flag,
        })
      );
    }
  });
  useReachBottom(() => {
    if (isMore) {
      getData(active + 1, pageNum + 1);
    }
  });
  return (
    <View className='relation-ship'>
      <Navbar title={navbarTitle} arrow='true'></Navbar>
      <View className='tab' style={{ top: navbarHeight }}>
        <Tabs active={active} onChange={onChange}>
          {tab.map(item => {
            return <Tab key={item.id} title={item.value}></Tab>
          })}
        </Tabs>
      </View>
      <View className='block'></View>
      <View className='list'>
        {!ListData.length && !isLoading ? <Empty description={active === 0 ? '暂无粉丝' : '暂无关注'} /> : (getListDom())}
      </View>
      {isLoading ? (
        <View className='loading'>
          <Loading color={themeColor} size='28px' />
        </View>
      ) : null}
      <Authorization canClose={false}></Authorization>
      <View>{showBackTop ? <BackTop top={.75 * screenHeight} /> : null}</View>
    </View>
  );
};

export default memo(Index);
